import React, { useState, useEffect } from 'react';
import { Table, Pagination, Spin, Alert, Modal } from 'antd';
import {request} from "../utils/requset";
import ApiUtils from '../utils/apiUtils';

const PzscLog = () => {
  // 定义状态变量
  // const [pageCount, setPageCount] = useState(0);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  // const [totalPage, setTotalPage] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [searchParams, setSearchParams] = useState({ key: '', value: '' }); // 搜索相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中行的状态
  const [tableHeight, setTableHeight] = useState(500); // 默认高度

  // 动态设置表格高度
  useEffect(() => {
    const updateTableHeight = () => {
      const viewportHeight = window.innerHeight;
      const desiredHeight = viewportHeight/2 - 100  ; // 例如，减去200像素用于其他内容
      setTableHeight(desiredHeight > 300 ? desiredHeight : 300); // 设置最小高度为300
    };

    updateTableHeight();
    window.addEventListener('resize', updateTableHeight);
    return () => window.removeEventListener('resize', updateTableHeight);
  }, []);

  // 获取数据的函数
  const fetchData = async (currentPage = 1, size = 10, search = { key: '', value: '' }) => {
    setLoading(true);
    setError(null);
    try {
      // 替换为你的实际 API URL
      const response = await request.post(ApiUtils.TD_LOG, {
        "gnlx":"pzbq",
        "pageNum":1,
        "pageSize":10,
        "userId":"14"}
      );

      const jsonData = response.data;

      // 设置分页相关的状态
      // setPageCount(jsonData.pageCount);
      setPageNum(jsonData.pageNum);
      setPageSize(jsonData.pageSize);
      setTotal(jsonData.total);
      // setTotalPage(jsonData.totalPage);

      // 设置表格数据源
      setDataSource(jsonData.data);
    } catch (err) {
      console.error('数据获取失败:', err);
      setError('数据获取失败，请稍后再试。');
    } finally {
      setLoading(false);
    }
  };

  // 在组件挂载时获取数据
  useEffect(() => {
    fetchData(pageNum, pageSize, searchParams);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageNum, pageSize, searchParams]);


  // 计算当前页显示的条数
  const startRow = (pageNum - 1) * pageSize + 1;
  const endRow = Math.min(pageNum * pageSize, total);

  const [visible, setVisible] = useState(false);
  const [modalContent, setModalContent] = useState('');

  const handleShowModal = (text) => {
    setModalContent(text);
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
  };
  const PzscLogTable = [
    {
      title: '运行时间',
      dataIndex: 'runtime',
      key: 'runtime',
      width: 60,
    },
    {
      title: '运行配置',
      dataIndex: 'config',
      key: 'config',
      width: 200,
    },
    {
      title: '是否成功运行',
      dataIndex: 'is_success',
      key: 'is_success',
      width: 70,
    },
    {
      title: '错误信息',
      dataIndex: 'message',
      key: 'message',
      width: 100,
      render: (text) => (
        <span>
          {text.length > 20 ? (
            <>
              {text.slice(0, 20)}...
              <a onClick={() => handleShowModal(text)}>查看</a>
            </>
          ) : (
            text
          )}
        </span>
      ),
    },
    {
      title: '文件路径',
      dataIndex: 'filepath',
      key: 'filepath',
      width: 120,
    },
  ];


  return (
    <div className="my-data-table-container">
      {/* <Title level={2}>入库单明细</Title> */}
      {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 16 }} />}
        
      <Spin spinning={loading}>
        <Table
          columns={PzscLogTable}
          dataSource={dataSource}
          rowKey="uuid"
          pagination={false} // 使用自定义的分页组件
          scroll={{ x: 'max-content', y: tableHeight }} // 启用水平和垂直滚动
          rowClassName={(record) =>
            selectedRowKeys.includes(record.id) ? 'selected-row' : ''
          }
        />
        <Modal
          title="错误信息"
          open={visible}
          onCancel={handleCancel}
          footer={null}
        >
          <p>{modalContent}</p>
        </Modal>
      </Spin>
      <div>
        <span>
          当前 {startRow}-{endRow} 条，共 {total} 条
        </span>
        <Pagination
          current={pageNum}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          pageSizeOptions={['10', '20', '50', '100']} // 限制每页条目数选项
          style={{ marginTop: 16, textAlign: 'right' }}
        />
      </div>
    </div>   
  );
};

export default PzscLog;
